<template>
  <div class="police-container">
    <!-- 页面标题和控制面板 -->
    <div class="police-header">
      <div class="header-left">
        <el-button
          type="default"
          @click="navigateToHome"
          icon="ArrowLeft"
          style="margin-right: 15px"
        >
          返回首页
        </el-button>
        <h1>缺陷查看数据</h1>
      </div>
      <div class="control-panel">
        <el-button
          v-if="!wsConnected"
          type="primary"
          @click="handleConnect"
          :loading="connecting"
        >
          连接WebSocket
        </el-button>
        <el-button
          v-else
          type="danger"
          @click="handleDisconnect"
        >
          断开连接
        </el-button>

        <el-button
          type="warning"
          @click="handleClearData"
          :disabled="policeList.length === 0"
        >
          清空数据
        </el-button>

        <el-button
          type="success"
          @click="addMockData"
        >
          添加测试数据
        </el-button>

        <div class="status-info">
          <span :class="['connection-status', wsConnected ? 'connected' : 'disconnected']">
            {{ wsConnected ? '已连接' : '未连接' }}
          </span>
          <span class="data-count">
            数据总数: {{ policeList.length }}
          </span>
        </div>
      </div>
    </div>

    <!-- 错误信息显示 -->
    <el-alert
      v-if="wsError"
      :title="wsError"
      type="error"
      :closable="false"
      show-icon
      style="margin-bottom: 20px"
    />

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="policeList"
        stripe
        border
        size="small"
        :height="600"
        empty-text="暂无数据"
      >
        <el-table-column prop="id" label="ID" width="80" fixed="left" />
        <el-table-column prop="realpol" label="检测点" width="120" />
        <el-table-column prop="speed" label="速度" width="100">
          <template #default="{ row }">
            {{ row.speed?.toFixed(2) || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="kmv" label="千米值" width="100">
          <template #default="{ row }">
            {{ row.kmv?.toFixed(2) || '-' }}
          </template>
        </el-table-column>

        <!-- 轴距相关 -->
        <el-table-column label="轴距" width="150">
          <template #default="{ row }">
            <div :style="{ backgroundColor: getStatusColor(row.zigStatus) }" class="status-cell">
              {{ row.zig?.toFixed(2) || '-' }}
            </div>
          </template>
        </el-table-column>

        <!-- 导高相关 -->
        <el-table-column label="导高" width="150">
          <template #default="{ row }">
            <div :style="{ backgroundColor: getStatusColor(row.heiSatus) }" class="status-cell">
              {{ row.hei?.toFixed(2) || '-' }}
            </div>
          </template>
        </el-table-column>

        <!-- 磨耗相关 -->
        <el-table-column label="磨耗" width="150">
          <template #default="{ row }">
            <div :style="{ backgroundColor: getStatusColor(row.MoHaoSatus) }" class="status-cell">
              {{ row.mohao?.toFixed(2) || '-' }}
            </div>
          </template>
        </el-table-column>

        <!-- 电压相关 -->
        <el-table-column label="电压" width="150">
          <template #default="{ row }">
            <div :style="{ backgroundColor: getStatusColor(row.fVotSatus) }" class="status-cell">
              {{ row.fVot?.toFixed(2) || '-' }}
            </div>
          </template>
        </el-table-column>

        <!-- 压力相关 -->
        <el-table-column label="压力" width="150">
          <template #default="{ row }">
            <div :style="{ backgroundColor: getStatusColor(row.fPressSatus) }" class="status-cell">
              {{ row.fPress?.toFixed(2) || '-' }}
            </div>
          </template>
        </el-table-column>

        <!-- 振动相关 -->
        <el-table-column label="振动" width="150">
          <template #default="{ row }">
            <div :style="{ backgroundColor: getStatusColor(row.fVibrationSatus) }" class="status-cell">
              {{ row.fVibration?.toFixed(2) || '-' }}
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="policeruleid" label="规则ID" width="100" />

        <!-- 时间戳 -->
        <el-table-column label="接收时间" width="180" fixed="right">
          <template #default="{ row }">
            {{ formatTimestamp(row.timestamp) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 状态说明 -->
    <div class="status-legend">
      <h3>状态说明</h3>
      <div class="legend-items">
        <div class="legend-item">
          <div class="legend-color normal"></div>
          <span>正常 (0)</span>
        </div>
        <div class="legend-item">
          <div class="legend-color warning"></div>
          <span>警告 (2)</span>
        </div>
        <div class="legend-item">
          <div class="legend-color danger"></div>
          <span>危险 (1)</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import {
  policeList,
  wsConnected,
  wsError,
  connectWebSocket,
  disconnectWebSocket,
  clearPoliceData,
  initPoliceService,
  addPoliceData
} from '@/services/policeService'
import { getStatusColor, PoliceStatus, type Police } from '@/types/police'

// 路由
const router = useRouter()

// 响应式数据
const connecting = ref(false)

// 导航函数
const navigateToHome = () => {
  router.push('/')
}

// 连接WebSocket
const handleConnect = async () => {
  connecting.value = true
  try {
    connectWebSocket()
    ElMessage.success('正在连接WebSocket...')
  } catch (error) {
    ElMessage.error('连接WebSocket失败')
    console.error(error)
  } finally {
    connecting.value = false
  }
}

// 断开WebSocket连接
const handleDisconnect = () => {
  disconnectWebSocket()
  ElMessage.info('已断开WebSocket连接')
}

// 清空数据
const handleClearData = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有缺陷数据吗？此操作不可恢复。',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    clearPoliceData()
    ElMessage.success('数据已清空')
  } catch {
    // 用户取消操作
  }
}

// 添加测试数据
const addMockData = () => {
  const mockData: Police = {
    id: Date.now(),
    realpol: `检测点-${Math.floor(Math.random() * 100)}`,
    speed: Math.random() * 120 + 20,
    kmv: Math.random() * 1000 + 100,
    zig: Math.random() * 50 + 10,
    hei: Math.random() * 20 + 5,
    zigStatus: Math.floor(Math.random() * 3) as PoliceStatus,
    heiSatus: Math.floor(Math.random() * 3) as PoliceStatus,
    mohao: Math.random() * 10 + 1,
    MoHaoSatus: Math.floor(Math.random() * 3) as PoliceStatus,
    fVot: Math.random() * 50 + 200,
    fVotSatus: Math.floor(Math.random() * 3) as PoliceStatus,
    fPress: Math.random() * 100 + 50,
    fPressSatus: Math.floor(Math.random() * 3) as PoliceStatus,
    fVibration: Math.random() * 30 + 5,
    fVibrationSatus: Math.floor(Math.random() * 3) as PoliceStatus,
    policeruleid: Math.floor(Math.random() * 10) + 1
  }

  addPoliceData(mockData)
  ElMessage.success('已添加测试数据')
}

// 格式化时间戳
const formatTimestamp = (timestamp?: number): string => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 生命周期钩子
onMounted(() => {
  // 初始化数据服务
  initPoliceService()

  // 可以自动连接WebSocket
  // handleConnect()
})

onUnmounted(() => {
  // 组件销毁时断开WebSocket连接
  disconnectWebSocket()
})
</script>

<style scoped>
.police-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.police-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.police-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.control-panel {
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 14px;
}

.connection-status {
  font-weight: bold;
}

.connection-status.connected {
  color: #67c23a;
}

.connection-status.disconnected {
  color: #f56c6c;
}

.data-count {
  color: #909399;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-cell {
  padding: 8px;
  border-radius: 4px;
  text-align: center;
  font-weight: bold;
  transition: background-color 0.3s ease;
}

.status-legend {
  margin-top: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-legend h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.legend-items {
  display: flex;
  gap: 30px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.legend-color.normal {
  background-color: transparent;
}

.legend-color.warning {
  background-color: rgba(255, 165, 0, 0.3);
}

.legend-color.danger {
  background-color: rgba(255, 69, 0, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .police-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  .control-panel {
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .legend-items {
    flex-wrap: wrap;
    gap: 15px;
  }
}
</style>